<?php

require '../vendor/autoload.php';

use LeanCloud\Query;
use LeanCloud\Object;
use LeanCloud\User;
use LeanCloud\CloudException;
use LeanCloud\Client;
use LeanCloud\Engine\LeanEngine;
use LeanCloud\Engine\Cloud;
use LeanCloud\Storage\CookieStorage;
/**
 * Created by PhpStorm.
 * User: issuser
 * Date: 2017/7/4
 * Time: 下午5:38
 */
class MatchingApi
{
    /*
     * 添加用户到匹配队列
     * */
    public static function addMatching($object, $user){

        $query = new Query("OrdinaryMatchingQueue");
        $query->equalTo("user", $user);
        $arr = $query->find();

        if (count($arr) > 0){
            Object::destroyAll($arr);
        }

        $matchingType = $object["matchingType"];
        $todoFolder = new Object("OrdinaryMatchingQueue"); // 构建对象
        $todoFolder->set("user", $user);
        $todoFolder->set("matchingType", $matchingType);
        $todoFolder->set("IP", $_SERVER['HTTP_X_REAL_IP']);            // 设置优先级

        self::sendMatchMessage($todoFolder, "594ceec4ac502e006072f6bc");

        try {
            $todoFolder->save();
            // 保存到服务端
        } catch (CloudException $ex) {
            // 失败
        }
    }


    /*
     * 匹配定时函数
     * */
    public static function matchingTimer(){

        $query = new Query("OrdinaryMatchingQueue");
        $arr = $query->find();

        while (count($arr) > 1){

            self::pairing($arr);
        }
    }

    /*
     * 用户分组
     * */
    public static function pairing($arr){

        $value1 = self::getRandUser($arr, "");

        $value2 = self::getRandUser($arr, $value1["IP"]);




        Object::destroyAll(array($value1, $value2));
    }



    /*
     * 发送匹配消息
     * */
    public static function sendMatchMessage($value, $conversationId){

//        $client = new GuzzleHttp\Client();

        $obj = (Object)$value;
        $user = $obj->get("user");
        $uUser = (Object)$user;

        $params = json_encode(array("from_peer" => "系统",
            "to_peers" => $uUser->getObjectId(),
            "conv_id" => $conversationId,
            "transient" => true,
            "message" => "匹配成功",
            "no_sync" => true), true);

        $headers = array(
            "X-LC-Id" => getenv("LC_APP_ID"),
            "X-LC-Key" => getenv("LC_APP_MASTER_KEY")
        );

        $data = Client::request("POST",
            "https://api.leancloud.cn/1.1/rtm/messages",
            $params, null, $headers, null);
//        assertArrayHasKey("objectId", $data);
//        $id = $data["objectId"];


        Client::delete("https://api.leancloud.cn/1.1/rtm/messages");



//        $res = $client->request('POST', 'https://api.leancloud.cn/1.1/rtm/messages', [
//
//            "form_params" => $params
//
//        ]);
//
//        error_log($res->getStatusCode());
//        error_log($res->getHeader('content-type'));
//        error_log($res->getBody());

    }

    /*
     * 获取随机用户IP
     * */
    public static function getRandUser($arr, $IP){

        $count = rand(0,count($arr)-1);
        $value = $arr[$count];

        if ($value["IP"] == $IP){

            return self::getRandUser($arr, $IP);

        }else {
            self::array_remove($arr, $count);
            return $value;
        }
    }

    /*
     * 删除数组中某个元素
     * */
    public static function array_remove(&$arr, $offset)
    {
        array_splice($arr, $offset, 1);
    }
















}